# coding=utf-8
"""
Author: Mr.夏末
@Function: app自动化关键字库
命令行启动appium服务: node "C:\Program Files\Appium\resources\app\node_modules\appium\build\lib\main.js"
"""
import json,time,os,threading
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from common.Logger import logger


class APP:

    def __init__(self):
        self.driver: webdriver.Remote = None

    def runappium(self, port='4723', appium_path='C:\Program Files\Appium'):
        """
        启动appium服务
        :param appium_path: appium安装根路径
        """
        if not appium_path:
            appium_path = 'C:\Program Files\Appium'

        if not port:
            port = '4723'

        self.port = port

        def runappium(appium_path,port):
            # 打开appium服务
            os.system(r'node "%s\resources\app\node_modules\appium\build\lib\main.js" -p %s >> appium.log' % (appium_path,port))

        # 创建一个线程,如果函数需要参数，就用args=传递
        th = threading.Thread(target=runappium, args=(appium_path,port))

        # 启动线程
        th.start()

    def run_app(self,conf='{}'):
        """
        启动APP
        :param conf:配置的json字符串
        """
        conf = json.loads(conf)
        # 连接appium服务器（回放之前一定要启动appium服务）
        self.driver = webdriver.Remote("http://127.0.0.1:%s/wd/hub" % self.port, conf)
        self.driver.implicitly_wait(30)

    def __find_ele(self,locator=''):
        """
        app元素定位
        :param locator: 支持ACCESSIBILITY_ID，ID，XPATH
        """
        if locator.startswith('(') or locator.startswith('/'):
            #xpath
            ele = self.driver.find_element(AppiumBy.XPATH,locator)
        elif locator.__contains__(":id/"):
            ele = self.driver.find_element(AppiumBy.ID,locator)
        else:
            ele = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID,locator)

        return ele

    def click(self,locator=''):
        """
        app点击
        :param locator: 支持ACCESSIBILITY_ID，ID，XPATH
        """
        ele = self.__find_ele(locator)
        ele.click()

    def input(self,locator='',value=''):
        """
        app输入
        :param locator: 支持ACCESSIBILITY_ID，ID，XPATH
        :param value: 输入的文本
        """
        ele = self.__find_ele(locator)
        ele.send_keys(value)

    def presskey(self,keycode='66'):
        """
        按键
        :param keycode: 键对应的键码
        """
        try:
            keycode = int(keycode)
            self.driver.keyevent(keycode)
        except:
            logger.warning("只支持数字keycode")
            pass

    def quit(self):
        self.driver.quit()

    def sleep(self,t='1'):
        try:
            t = float(t)
        except:
            t = 1

        time.sleep(t)

    def closeappium(self):
        # 关闭appium
        os.system('taskkill /F /IM node.exe')